59. 螺旋矩阵 II

48. 旋转图像

题目

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

提示:

1
2
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

1
2
输入:n = 1
输出:[[1]]

提示:

  • 1 <= n <= 20

主要思路

按层遍历

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n,vector<int>(n));
int num=1;

int left = 0, right=n-1, top = 0, bottom=n-1;

while(left<=right && top<=bottom){
int i= left;
while(i<=right){
matrix[top][i] = num;
i++;
num++;
}

i=top+1;
while(i<=bottom){
matrix[i][right] = num;
i++;
num++;
}

i=right-1;
while(i>=left){
matrix[bottom][i]=num;
i--;
num++;
}
i=bottom-1;
while(i>top){
matrix[i][left]=num;
i--;
num++;
}

top++;
bottom--;
left++;
right--;
}
return matrix;

}
};